import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store' // Vuex，用于判断登录状态

Vue.use(Router)

// 路由配置
const router = new Router({
    mode: 'history', // or 'hash' based on your preference
    routes: [
        {
            path: '/',
            name: 'Home',
            component: () => import('@/views/Home.vue')
        },
        {
            path: '/forum',
            name: 'Forum',
            component: () => import('@/views/Forum.vue')
        },{
            path: '/foods',
            name: "Foods",
            component: () => import('@/views/Foods.vue')
        },{
            path: "/culture",
            name: "Culture",
            component: () => import('@/views/Culture.vue')
        },{
            path: "/culturedetail/:id",
            name: "/CultureDetail",
            component: () => import('@/views/CultureDetail.vue')
        },
        {
            path: "/agriculturals",
            name: "Agriculturals",
            component: () => import('@/views/Agriculturals.vue')
        },
        {
            path: "/agriculturalsdetail/:id",
            name: "ActivitiesDetail",
            component: () => import('@/views/AgriculturalsDetail.vue')
        },
        {
            path: "/accommodations",
            name: "Accommodations",
            component: () => import('@/views/Accommodations.vue')
        },{
            path: "/accommodationsdetail/:id",
            name: "AccommodationsDetail",
            component: () => import('@/views/AccommodationsDetail.vue')
        },
        {
            path: "/scenic",
            name: "Scenic",
            component: () => import('@/views/Scenic.vue')
        },
        {
            path: "/scenicdetail/:id",
            name: "ScenicDetail",
            component: () => import('@/views/ScenicDetail.vue')
        },
        {
            path: "/activities",
            name: "Activities",
            component: () => import('@/views/Activities.vue')
        },
        {
            path: "/activitiesDetail/:id",
            name: "ActivitiesDetail",
            component: () => import('@/views/ActivitiesDetail.vue')
        },
        {
            path: "/tickets",
            name: "Tickets",
            component: () => import('@/views/Tickets.vue')
        },
        {
            path: "/car",
            name: "PersonalOrderCart",
            component: () => import('@/views/Car.vue')
        },

        {
            path: '/login',
            name: 'Login',
            component: () => import('@/views/Login.vue')
        },
        {
            path: '/register',
            name: 'Register',
            component: () => import('@/views/Register.vue')
        },
        {
            path: "/profile",
            name: "Profile",
            component: () => import("@/views/user/profile/index"),
        },
        {
            path: "/map",
            name: "Map",
            component: () => import('@/views/Map.vue')
        }
    ]
})

// 全局路由守卫
router.beforeEach(async (to, from, next) => {
    // 1. 确定token来源
    const token = store.state.token || localStorage.getItem('token')

    // 2. 处理不需要认证的路由
    if (!to.meta.requiresAuth) {
        next()
        return
    }

    // 3. 需要认证的路由处理
    if (token) {
        // 3.1 检查用户信息是否已加载
        if (!store.state.name || store.state.roles.length === 0) {
            try {
                // 3.2 获取用户信息
                await store.dispatch('getInfo')

                // 3.3 检查权限是否满足路由要求
                if (to.meta.roles && !hasPermission(store.state.roles, to.meta.roles)) {
                    next({ path: '/401' }) // 无权限页面
                    return
                }

                next()
            } catch (error) {
                // 3.4 获取用户信息失败处理
                console.error('获取用户信息失败:', error)
                await store.dispatch('logout')
                next({
                    path: '/login',
                    query: { redirect: to.fullPath }
                })
            }
        } else {
            // 3.5 用户信息已存在，检查权限
            if (to.meta.roles && !hasPermission(store.state.roles, to.meta.roles)) {
                next({ path: '/401' }) // 无权限页面
                return
            }
            next()
        }
    } else {
        // 4. 无token跳转登录
        next({
            path: '/login',
            query: { redirect: to.fullPath }
        })
    }
})

// 权限检查方法
function hasPermission(userRoles, routeRoles) {
    if (!routeRoles) return true
    return userRoles.some(role => routeRoles.includes(role))
}

export default router
